<template>
  <div class="message-list-container">
    <h2>我的消息</h2>
    
    <el-row :gutter="20">
      <!-- 左侧联系人列表 -->
      <el-col :span="6">
        <el-card class="contact-list-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>对话列表</span>
              <el-button type="primary" size="small" @click="loadContacts">刷新</el-button>
            </div>
          </template>
          
          <el-empty v-if="contactList.length === 0 && !loading" description="暂无消息"></el-empty>
          
          <div v-else class="contact-list">
            <div 
              v-for="contact in contactList" 
              :key="contact.userId" 
              class="contact-item"
              :class="{'active': currentContact && currentContact.userId === contact.userId}"
              @click="selectContact(contact)"
            >
              <div class="contact-avatar">
                <el-avatar :size="40" :icon="UserFilled"></el-avatar>
                <div v-if="contact.unreadCount > 0" class="unread-badge">{{contact.unreadCount}}</div>
              </div>
              <div class="contact-info">
                <div class="contact-name">
                  {{ contact.name }}
                  <el-tag size="small" v-if="contact.userType === 'company'">企业</el-tag>
                  <el-tag size="small" type="success" v-else>零工</el-tag>
                </div>
                <div class="contact-preview">{{ contact.lastMessage }}</div>
              </div>
              <div class="contact-time">{{ formatMessageTime(contact.lastTime) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧消息内容 -->
      <el-col :span="18">
        <el-card class="message-content-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span v-if="currentContact">
                {{ currentContact.name }} 
                <el-tag size="small" v-if="currentContact.userType === 'company'">企业</el-tag>
                <el-tag size="small" type="success" v-else>零工</el-tag>
                <span v-if="taskInfo" class="task-info-tag">
                  关联任务: {{ taskInfo }}
                </span>
              </span>
              <span v-else>选择联系人开始对话</span>
            </div>
          </template>
          
          <el-empty v-if="!currentContact" description="请从左侧选择对话"></el-empty>
          
          <div v-else>
            <div class="message-chat-container">
              <div ref="chatContainer" class="message-chat-list">
                <div v-if="currentMessages.length === 0" class="empty-chat">
                  <el-empty description="暂无消息记录，发送消息开始对话"></el-empty>
                </div>
                <div 
                  v-for="(msg, index) in currentMessages" 
                  :key="msg.id"
                  class="message-bubble"
                  :class="{'self-message': isSelfMessage(msg), 'other-message': !isSelfMessage(msg)}"
                >
                  <div class="message-time" v-if="showMessageDate(msg, index)">
                    {{ formatDate(msg.createTime) }}
                  </div>
                  <div class="message-wrapper">
                    <div class="message-content">
                      <p>{{ msg.content }}</p>
                    </div>
                    <div class="message-status">
                      <span v-if="!msg.isRead && !isSelfMessage(msg)" class="unread-tag">未读</span>
                      <span class="message-time-small">{{ formatMessageTime(msg.createTime) }}</span>
                      <div v-if="msg.taskId" class="message-task">
                        <el-button 
                          type="text" 
                          size="small" 
                          @click="handleViewTask(msg.taskId)"
                        >
                          任务详情
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="message-input-container">
                <div v-if="replyForm.taskId" class="task-tip">
                  当前对话关联任务ID: {{ replyForm.taskId }}
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="handleViewTask(replyForm.taskId)"
                  >
                    查看任务
                  </el-button>
                </div>
                <el-form :model="replyForm" ref="replyFormRef" :rules="replyRules">
                  <el-form-item prop="content">
                    <el-input
                      v-model="replyForm.content"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入消息内容"
                      @keyup.enter.ctrl="handleSendReply"
                    />
                  </el-form-item>
                  <el-form-item>
                    <div class="send-tips">提示: 按 Ctrl+Enter 发送消息</div>
                    <el-button type="primary" @click="handleSendReply">发送</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getMessageList, markAsRead, sendMessage, getContactList, getConversation } from '@/api/message'
import { formatDate } from '@/utils/format'
import { UserFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const router = useRouter()
const loading = ref(false)
const contactList = ref([])
const currentContact = ref(null)
const taskInfo = ref('')
const currentMessages = ref([])
const chatContainer = ref(null)
const replyForm = ref({
  receiverId: null,
  taskId: null,
  content: ''
})
const replyRules = {
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' }
  ]
}
const replyFormRef = ref(null)
const userType = ref(localStorage.getItem('userType') || 'worker')
const userId = ref(localStorage.getItem('userId') || null)

// WebSocket连接
let ws = null

// 格式化消息时间
const formatMessageTime = (time) => {
  if (!time) return '';
  
  const now = dayjs();
  const messageTime = dayjs(time);
  
  if (now.diff(messageTime, 'day') === 0) {
    // 今天
    return messageTime.format('HH:mm');
  } else if (now.diff(messageTime, 'day') === 1) {
    // 昨天
    return '昨天 ' + messageTime.format('HH:mm');
  } else if (now.diff(messageTime, 'year') === 0) {
    // 今年
    return messageTime.format('MM-DD HH:mm');
  } else {
    // 更早
    return messageTime.format('YYYY-MM-DD HH:mm');
  }
};

// 判断是否显示日期分割线
const showMessageDate = (message, index) => {
  if (index === 0) return true;
  
  const currentDate = dayjs(message.createTime).format('YYYY-MM-DD');
  const prevDate = dayjs(currentMessages.value[index - 1].createTime).format('YYYY-MM-DD');
  
  return currentDate !== prevDate;
};

// 判断消息是否是自己发送的
const isSelfMessage = (message) => {
  console.log('判断消息发送者:', message.senderId, userId.value, String(message.senderId) === String(userId.value));
  return String(message.senderId) === String(userId.value);
};

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

// 加载联系人列表
const loadContacts = async () => {
  loading.value = true;
  try {
    const response = await getContactList();
    if (response.code === 200 && response.data) {
      contactList.value = response.data;
    } else {
      ElMessage.error(response.message || '获取联系人列表失败');
    }
  } catch (error) {
    console.error('加载联系人列表失败:', error);
    ElMessage.error('获取联系人列表失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 选择联系人
const selectContact = async (contact) => {
  currentContact.value = contact;
  
  // 设置回复表单数据
  replyForm.value.receiverId = contact.userId;
  replyForm.value.taskId = contact.taskId || null;
  replyForm.value.content = '';
  
  taskInfo.value = contact.taskTitle || '';
  
  // 加载对话消息
  await loadConversationMessages(contact.userId);
  
  // 滚动到最新消息
  scrollToBottom();
};

// 加载与特定联系人的对话
const loadConversationMessages = async (contactId) => {
  loading.value = true;
  try {
    const response = await getConversation(contactId);
    if (response.code === 200 && response.data) {
      currentMessages.value = response.data;
      console.log('当前用户ID:', userId.value);
      console.log('加载的消息:', response.data);
      
      // 自动标记消息为已读
      await markUnreadMessages();
    } else {
      ElMessage.error(response.message || '获取对话消息失败');
    }
  } catch (error) {
    console.error('加载对话消息失败:', error);
    ElMessage.error('获取对话消息失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 标记未读消息为已读
const markUnreadMessages = async () => {
  const unreadMessages = currentMessages.value.filter(
    msg => !msg.isRead && !isSelfMessage(msg)
  );
  
  if (unreadMessages.length === 0) return;
  
  for (const msg of unreadMessages) {
    try {
      await markAsRead(msg.id);
      msg.isRead = true;
    } catch (error) {
      console.error('标记消息已读失败:', error);
    }
  }
  
  // 更新联系人未读消息数量
  if (currentContact.value) {
    currentContact.value.unreadCount = 0;
  }
};

// 发送回复
const handleSendReply = async () => {
  if (!replyForm.value.content.trim()) {
    ElMessage.warning('请输入消息内容');
    return;
  }
  
  try {
    await replyFormRef.value.validate();
    
    const messageData = {
      receiverId: replyForm.value.receiverId,
      taskId: replyForm.value.taskId,
      content: replyForm.value.content.trim()
    };
    
    const response = await sendMessage(messageData);
    
    if (response.code === 200 && response.data) {
      // 清空输入框
      replyForm.value.content = '';
      
      // 添加到消息列表
      const newMessage = {
        id: response.data,
        senderId: userId.value,
        receiverId: replyForm.value.receiverId,
        taskId: replyForm.value.taskId,
        content: messageData.content,
        isRead: false,
        createTime: new Date().toISOString(),
        senderName: localStorage.getItem('username') || '我'
      };
      
      currentMessages.value.push(newMessage);
      
      // 滚动到最新消息
      scrollToBottom();
    } else {
      ElMessage.error(response.message || '发送消息失败');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败: ' + (error.message || '未知错误'));
  }
};

// 查看任务详情
const handleViewTask = (taskId) => {
  router.push(`/task/${taskId}`);
};

// 建立WebSocket连接
const connectWebSocket = () => {
  if (!userId.value) return;
  
  const wsUrl = `ws://${window.location.host}/api/ws/messages/${userId.value}`;
  ws = new WebSocket(wsUrl);
  
  ws.onopen = () => {
    console.log('聊天WebSocket连接已建立');
  };
  
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      if (data.type === 'new_message') {
        // 收到新消息，检查是否为当前对话中的消息
        const message = data.message;
        
        if (currentContact.value && (
          (String(message.senderId) === String(currentContact.value.userId)) || 
          (String(message.receiverId) === String(currentContact.value.userId))
        )) {
          // 添加到当前对话
          currentMessages.value.push(message);
          scrollToBottom();
          
          // 如果是收到的消息，标记为已读
          if (!isSelfMessage(message)) {
            markAsRead(message.id);
          }
        } else {
          // 更新联系人列表中的未读计数
          updateContactUnreadCount(message.senderId);
          
          // 通知用户有新消息
          if (!isSelfMessage(message)) {
            ElMessage.info(`收到来自 ${message.senderName} 的新消息`);
          }
        }
      }
    } catch (e) {
      console.error('处理WebSocket消息时出错:', e);
    }
  };
  
  ws.onclose = () => {
    console.log('聊天WebSocket连接已关闭');
    // 尝试重新连接
    setTimeout(connectWebSocket, 3000);
  };
  
  ws.onerror = (error) => {
    console.error('聊天WebSocket错误:', error);
  };
};

// 更新联系人未读消息计数
const updateContactUnreadCount = (senderId) => {
  const contact = contactList.value.find(c => String(c.userId) === String(senderId));
  if (contact) {
    contact.unreadCount = (contact.unreadCount || 0) + 1;
  } else {
    // 如果联系人不在列表中，刷新联系人列表
    loadContacts();
  }
};

// 监听当前联系人变化，更新对话内容
watch(currentContact, () => {
  if (currentContact.value) {
    const contact = contactList.value.find(c => c.userId === currentContact.value.userId);
    if (contact) {
      contact.unreadCount = 0;
    }
  }
});

// 组件挂载时加载数据和建立WebSocket连接
onMounted(() => {
  loadContacts();
  connectWebSocket();
});

// 组件卸载时关闭WebSocket连接
onBeforeUnmount(() => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.close();
  }
});
</script>

<style scoped>
.message-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contact-list-card, .message-content-card {
  height: calc(100vh - 180px);
}

.contact-list {
  height: calc(100% - 20px);
  overflow-y: auto;
}

.contact-item {
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.contact-item:hover {
  background-color: #f5f7fa;
}

.contact-item.active {
  background-color: #ecf5ff;
}

.contact-avatar {
  position: relative;
  margin-right: 10px;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.contact-info {
  flex: 1;
  overflow: hidden;
}

.contact-name {
  font-weight: bold;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.contact-name .el-tag {
  margin-left: 5px;
}

.contact-preview {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.contact-time {
  font-size: 12px;
  color: #909399;
  min-width: 80px;
  text-align: right;
}

.message-chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 250px);
}

.message-chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message-bubble {
  margin-bottom: 20px;
}

.message-time {
  text-align: center;
  margin: 10px 0;
  font-size: 12px;
  color: #909399;
}

.message-wrapper {
  display: inline-block;
  max-width: 80%;
}

.self-message .message-wrapper {
  float: right;
}

.message-content {
  display: inline-block;
  padding: 10px 15px;
  border-radius: 4px;
  word-break: break-word;
}

.self-message {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.self-message .message-content {
  background-color: #e1f3d8;
  color: #606266;
  border-top-right-radius: 0;
  text-align: left;
}

.other-message .message-content {
  background-color: #f2f6fc;
  color: #606266;
  border-top-left-radius: 0;
}

.message-status {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.self-message .message-status {
  text-align: right;
}

.other-message .message-status {
  text-align: left;
}

.unread-tag {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 10px;
  margin-right: 5px;
}

.message-time-small {
  color: #c0c4cc;
}

.message-task {
  display: inline-block;
  margin-left: 10px;
}

.message-input-container {
  padding: 10px;
  border-top: 1px solid #f0f0f0;
}

.send-tips {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
  float: left;
}

.empty-chat {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    margin-bottom: 20px;
  }
  
  .contact-list-card, .message-content-card {
    height: auto;
  }
  
  .contact-list {
    max-height: 250px;
  }
  
  .message-chat-list {
    max-height: 300px;
  }
}

.task-info-tag {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.task-tip {
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 